﻿using EnvDTE;
using Microsoft.VisualStudio.Shell;

namespace Language.Utility
{
    public static class Goto
    {
        #region Public Functions

        public static void Symbol( Stub.DetailedContext context )
        {
            Symbol( context.File, context.Line, context.Position.Start, context.LineStart );
        }

        public static void Symbol( Stub.Symbol symbol )
        {
            Symbol( symbol.File, symbol.Line, 0 );
        }

        public static void Symbol( string file, int line, int startPosition = 1, int lineStart = 0 )
        {
            DTE dte = (DTE)ServiceProvider.GlobalProvider.GetService( typeof( DTE ) );

            ProjectItem item = dte.Solution.FindProjectItem( file );

            if ( item != null )
            {
                // EnvDTE starts counting from 1
                int adjustedLine = line + 1;
                int lineOffset = ( startPosition - lineStart ) + 1;

                item.Open();
                TextDocument document = (TextDocument)item.Document.Object();

                EditPoint editPoint = document.CreateEditPoint();

                editPoint.MoveToLineAndOffset( adjustedLine, lineOffset );
                editPoint.TryToShow();

                TextSelection selection = item.Document.Selection as TextSelection;

                if ( selection != null )
                {
                    selection.MoveToLineAndOffset( adjustedLine, lineOffset );
                }
            }
        }



        #endregion Public Functions
    }
}
